import React from 'react';
import { connect } from 'dva';
import { Button, Table, Form, Input, Popconfirm, Select,TreeSelect,   } from 'antd';
const FormItem = Form.Item;
const Option = Select.Option;
const TreeNode = TreeSelect.TreeNode;

import UpdateApplyModal from '../../components/using/UpdateApplyModal';
import AddApplyModal from '../../components/using/AddApplyModal';
import ApplyModal from '../../components/using/ApplyModal';
import DistributionViewModal from '../../components/using/DistributionViewModal';

function Apply({ dispatch, apply, loading, form }) {

    const { getFieldDecorator, getFieldsValue, getFieldValue } = form;
    const { currentItem, modalVisible, detailModalType,modalType,detailList,assetTypeTree } = apply

    const treeData = (i) => {
        return i.map( d => {
          d.label = d.name;
          d.key = d.id_+'';
          d.value = d.id_+'';
          d.children = d.depts && d.depts.length > 0 ? treeData(d.depts) : [];
          return d;
        })
    }

    const typeTreeData = (i) => {
        return i.map( d => {
          d.label = d.name;
          d.key = d.id_+'';
          d.value = d.id_+'';
          d.children = d.assetType && d.assetType.length > 0 ? typeTreeData(d.assetType) : [];
          return d;
        })
    }

    const columns = [{
        title: '申请单号',
        dataIndex: 'usingApplyId_',
        key: 'usingApplyId_',
        width: 120,
    },{
        title: '领用部门',
        dataIndex: 'branchName',
        key: 'branchName',
        width: 100,
    },{
        title: '领用人',
        dataIndex: 'userName',
        key: 'userName',
        width: 100,
    },{
        title: '资产分类',
        dataIndex: 'typeName',
        key: 'typeName',
        width: 80,
    },{
        title: '申请时间',
        dataIndex: 'createTime',
        key: 'createTime',
        width: 100,
    },{
        title: '状态',
        dataIndex: 'status',
        key: 'status',
        width: 60,
        render: (value, row, index) => {
            return (
                //value==1?"未处理":value==2?"处理中":value==3?"已完成":'停用'
                value==1?"未分配":value==2?"已分配":''
            )
        }
    },{
        title: '操作员',
        dataIndex: 'operator',
        key: 'operator',
        width: 80,
    },{
        title: '更新时间',
        dataIndex: 'updateTime',
        key: 'updateTime',
        width: 100,
    },{
        title: '操作',
        key: 'operation',
        width: 100,
        render: (text, record) => (
            <span>
            {(record.status==1)?(
              <span>
                <UpdateApplyModal title="编辑单号" record={record} assetType={assetTypeTree} onOk={editHandler.bind(null, record.id_)}>
                  <a>编辑</a>
                </UpdateApplyModal>
                <span className="ant-divider" />
                <Popconfirm title="确认删除？" onConfirm={deleteHandler.bind(null, record.id_)}>
                <a>删除</a>
                </Popconfirm>
              </span>
            ):<a onClick={onViewItem.bind(null, record.id_)}>查看</a>}



            </span>
        ),
    }];

    const pagination = {
        current:apply.current,
        pageSize:apply.currentSize,
        total: apply.total,
        showSizeChanger: true,
        showTotal: (total => '共' + apply.total + '条'),
        onShowSizeChange(current, size) {
            dispatch({
                type: 'apply/queryList',
                payload: { ...getFieldsValue(),...{'pageNum':current, 'pageSize':size} },
            });
        },
        onChange(current) {
            dispatch({
                type: 'apply/queryList',
                payload: { ...getFieldsValue(),...{'pageNum':current, 'pageSize':apply.currentSize} },
            });
        },
    };

    const onViewItem = (id) => {
       dispatch({
            type: 'apply/onViewItem',
            payload:id,
        })
    }
    const editHandler = (id, values) => {
        dispatch({
            type: 'apply/edit',
            payload: { id, ...values },
        });
    }
    const addDetailHandler = (values) => {
         detailList.push(values);
         dispatch({
            type: 'apply/changeDetailList',
            payload:detailList,
         });
    }
 
    function deleteHandler(id) {
        dispatch({
            type: 'apply/remove',
            payload: {id:id,search:{...getFieldsValue()}},
        });
    }
    const submitHandle = () => {
        dispatch({
            type: 'apply/queryList',
            payload: { ...getFieldsValue() },
        });
    }

    function handleClear(){
      form.resetFields();
    }

    const addHandler = () => {
        dispatch({
        type: 'apply/showModal',
            payload: {
                modalType: 'create',
            },
        })
    }

    const modalProps = {
        item: modalType === 'create' ? {} : apply.currentItem,
        visible: modalVisible,
        type: modalType,
        maskClosable: false,
        dispatch: dispatch,
        deptTree:apply.deptTree,
        userList:apply.userList,
        assetType:assetTypeTree,
        detailList:detailList,
        confirmLoading: loading,
        title: `${modalType === 'create' ? '新增领用申请' : '编辑领用申请'}`,
        wrapClassName: 'vertical-center-modal',
        newKey : apply.newKey1,
        onOk (data) {
           dispatch({
                type: `apply/createApply`,
                payload: data,
            })
        },
        onCancel () {
            dispatch({
                type: 'apply/hideModal',
            })
        },
    }
    const detailModalProps = {
        item: apply.detailItem,        
        assetType:assetTypeTree,
        visible: apply.detailModalVisible,
        maskClosable: false,
        confirmLoading: loading,
        title: `${detailModalType === 'create' ? '新增领用申请详情' : '编辑申请单详情'}`,
        wrapClassName: 'vertical-center-modal',
        newKey : apply.newKey2,
        onOk (data) {
            if(detailModalType==='create'){
                 detailList.push(data);
            }else{
                for(var i=0;i<detailList.length;i++){  
                    if(detailList[i].id==data.id){
                        detailList[i].desc=data.desc;
                        detailList[i].typeVo=data.typeVo;
                    }
                }
            }
            dispatch({
                type: 'apply/saveDetailList',
                payload:detailList,
            });
            
        },
        onCancel () {
            dispatch({
                type: 'apply/hideApplyDetail',
            })
        },
    }
    const viewModalProps = {
        item: apply.viewItem,
        visible: apply.viewModalVisible,
        maskClosable: false,
        viewDetailList:apply.viewDetailList,
        confirmLoading: loading,
        title: '查看申请单',
        wrapClassName: 'vertical-center-modal',
        newKey : apply.newKey,
        onCancel () {
            dispatch({
                type: 'apply/hideViewModal',
            })
        },
    }

    return (
        <div style={{backgroundColor:'#fff'}}>
          <div style={{minHeight:'100%'}}>
              <div style={{width:'100%',backgroundColor:'#fff',lineHeight:'40px',paddingLeft:'20px',paddingTop:'10px'}}>
                  <Form layout="inline" >
                    <FormItem>
                            {
                            getFieldDecorator('branchId')(
                            <TreeSelect
                                style={{ width: 220 }}
                                showSearch
                                treeNodeFilterProp="title"
                                dropdownStyle={{ maxHeight: 400, overflow: 'auto' }}
                                placeholder="请选择领用部门"
                                allowClear
                                treeData={treeData(apply.deptTree)}
                                treeDefaultExpandAll
                            >                            
                            </TreeSelect>
                            )
                         }
                    </FormItem>
                    <FormItem>
                            {getFieldDecorator('userName')(
                                <Input type="text" placeholder="领用人" style={{ width:'150px' }} />
                            )}
                    </FormItem>
                    <FormItem>
                         {
                            getFieldDecorator('typeId')(
                            <TreeSelect
                                style={{ width: 220 }}
                                showSearch
                                treeNodeFilterProp="title"
                                dropdownStyle={{ maxHeight: 400, overflow: 'auto' }}
                                placeholder="请选择资产分类"
                                allowClear
                                treeDefaultExpandAll
                                treeData={typeTreeData(assetTypeTree)}
                            >                              
                            </TreeSelect>
                            )
                         }
                    </FormItem>

                    <FormItem>
                        {getFieldDecorator('status')(
                            <Select
                                showSearch   
                                style={{ width: 100 }}
                                placeholder="选择状态"
                                optionFilterProp="children"
                        >
                              <Option value="">全部</Option>
                              <Option value="1">未分配</Option>
                              <Option value="2">已分配</Option>
                            </Select>
                        )}
                    </FormItem>
                    <FormItem>
                        <Button type="primary" size='large' onClick={submitHandle} className='ant-search-btn'>查询</Button>
                    </FormItem>
                    <FormItem>
                        <Button size="large" htmlType="reset" onClick={handleClear}>清空</Button>
                    </FormItem>
                    <div style={{marginTop:'-40px',textAlign:'right',paddingRight:'10px'}}>
                       <FormItem>
                         <Button size="large" style={{ marginRight: '10px' }} type="primary" onClick={addHandler}>新增申请</Button>
                       </FormItem>
                    </div>
                </Form>
            </div>

            <div style={{width:'100%',padding:"30px 20px",}}>
                <Table columns={columns} rowKey={record => record.id_} loading={loading} dataSource={apply.list} pagination={pagination}
                />
            </div>
            </div>

            <AddApplyModal {...modalProps} />
            <ApplyModal {...detailModalProps} />
            <DistributionViewModal {...viewModalProps} />
        </div>
    );
}

function mapStateToProps(state) {
  return { apply : state.apply,loading:state.loading.models.apply};
}

Apply = Form.create()(Apply);

export default connect(mapStateToProps)(Apply);
